from vosk import Model, KaldiRecognizer
import os
import json
import threading
from ..utils import service_functions
import configs
from ..configs import languages
from template.singleton import Singleton


class Speech_recognition:
    """Класс распознавания речи"""

    def recognition(self) -> None:
        """Функция распознавания речи.

        Функция работает в цикле и отправлет распознаную строку.

        В очередь queue в объект **stream_speech**.

        Функция становиться на паузу во время синтеза речи.
        """

        stop = "False"
        flag = True
        check = service_functions.Cheek_Queue(stop, flag)
        if not os.path.exists(configs.model_mini_way):

            print(languages["speech_recognition"][self.recognition.__name__]["error"])
            exit(1)

        import pyaudio

        model = Model(configs.model_mini_way)
        rec = KaldiRecognizer(model, 16000)
        p = pyaudio.PyAudio()
        stream = p.open(
            format=pyaudio.paInt16,
            channels=1,
            rate=16000,
            input=True,
            frames_per_buffer=8000,
        )
        while True:
            check.set_Queue(configs.stop_sr)
            state = check.cheek_Queue()
            if not state:
                stream.stop_stream()
            if state:
                stream.start_stream()
            if state:
                data = stream.read(4000)
                if len(data) == 0:
                    break
                if rec.AcceptWaveform(data) and configs.resualt_sr == 0:
                    recognizer_json = rec.Result()
                    recognized_data = json.loads(recognizer_json)
                    recognized_str = recognized_data["text"]
                    if len(recognized_str) > 0 and recognized_str != " ":
                        # print(recognized_str,222,"\n\t")
                        configs.stream_speech.put(recognized_str)
                        pass
                    else:
                        pass
                """
                else:
                    recognizer_json = rec.PartialResult()
                    recognized_data = json.loads(recognizer_json)
                    recognized_str = recognized_data['partial']
                    if len(recognized_str) > 0:
                        print(recognized_str)
                        #config.stream_speech_partial.put(recognized_str)
                        #pass
                        config.stream_speech.put(recognized_str)
                    else:
                        pass
                    """

    def start_recognition(self) -> None:
        """Функция генерации потока распознавания речи"""
        my_thread = threading.Thread(target=self.recognition)
        my_thread.start()
